package org.sanguine.tests.tenderpro.actions;

import org.sanguine.tests.tenderpro.actions.Action;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Author: Alexey Kuznetsov
 * Date: 20.02.14
 * Time: 11:50
 * SVN $Id$
 */
public class FindClassForAction extends DefaultHandler implements Action {
    private final static String NAME_ELEMENT = "name";
    private final static String CLASS_ELEMENT = "class";

    private String[] className = new String[1];
    private String actionName;
    private boolean actionFound = false;
    private boolean classFound = false;
    private boolean startActionName;
    private boolean startClassName;
    private String foundClassName;
    private String value;



    public void setUp(List<Object> params) {
        if (params == null
                || params.size() != 2
                || params.get(0) == null
                || !(params.get(0) instanceof String)
                || ((String) params.get(0)).isEmpty()
                || params.get(1) == null
                || !(params.get(1) instanceof String[])) {

            actionFound = true;
            classFound =  true;
            className[0] = null;
            return;
        }
        actionName = ((String)params.get(0)).trim();
        className = (String[])params.get(1);
    }

    @Override
    public void endDocument() throws SAXException {
        if (classFound) className[0] = foundClassName;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (classFound) return;
        if (localName.equals(NAME_ELEMENT) && !startActionName) {
            startActionName = true;
            return;
        }
        if (localName.equals(CLASS_ELEMENT)) {
            startClassName = true;
            return;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (localName.equals(NAME_ELEMENT) && startActionName) {
            startActionName = false;
            if (value != null && value.equals(actionName)) {
                actionFound = true;

            }
            return;
        }
        if (localName.equals(CLASS_ELEMENT)) {
            startClassName = true;
            return;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
    }

    @Override
    public void doAction(List<String> params) {

    }
}
